<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/26 00:10:58 $)
// $RCSfile: functions_downloads.php,v $ : $Revision: 1.11 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Deletes a given category
*/
function deleteDownloadCategory($downloadcategoryid)
{
	global $dbCore;

	// Get all child categories
	$downloadcategoryidlist = array();
	$downloadcategoryidlist = fetchChildCategories($downloadcategoryid, ($_temp = array()));
	$downloadcategoryidlist[] = $downloadcategoryid;

	// First Get all the items under these categories
	$downloaditemidlist = array();
	$dbCore->query("SELECT `downloaditemid` FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloadcategoryid` IN (". buildIN($downloadcategoryidlist) .");");
	while ($dbCore->nextRecord())
	{
		$downloaditemidlist[] = $dbCore->Record["downloaditemid"];
	}

	// Ok now nuke all the items and their descriptions first
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloaditemid` IN (". buildIN($downloaditemidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."downloaddesc` WHERE `downloaditemid` IN (". buildIN($downloaditemidlist) .");");

	// Nuke the categories
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."downloadcategories` WHERE `downloadcategoryid` IN (". buildIN($downloadcategoryidlist) .");");

	deleteTemplateGroupAssignLinks(array($downloadcategoryid), TGROUP_DOWNLOADS);

	rebuildDownloadJSCache();

	return count($downloadcategoryidlist);
}

/**
* Fetches the ids of all child Categories
*/
function fetchChildCategories($downloadcategoryid, &$tslist)
{
	global $dbCore;

	if (empty($tslist))
	{
		$tslist = array();
	}

	$newlist = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."downloadcategories` WHERE `parentcategoryid` = '". intval($downloadcategoryid) ."';");
	while($dbCore->nextRecord()) {
		if (!in_array($dbCore->Record["downloadcategoryid"], $tslist))
		{
			$tslist[] = $dbCore->Record["downloadcategoryid"];
			$newlist[] = $dbCore->Record["downloadcategoryid"];
		}
	}

	if (_is_array($newlist))
	{
		foreach ($newlist as $key=>$val)
		{
			fetchChildCategories($val, $tslist);
		}
	}

	return $tslist;
}

/**
* Update a download file to the database
*/
function updateDownloadFile($downloaditemid, $downloadcategoryid, $title, $description, $filelink, $displayorder, $enablepassword, $itempassword)
{
	global $dbCore, $_SWIFT;

	$_downloaditem = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."downloaditems` WHERE downloaditemid = '". intval($downloaditemid) ."';");

	// Are we supposed to upload a file or just link over to an existing one?
	if (empty($filelink) && $_FILES["downloadfile"]["error"] == UPLOAD_ERR_OK)
	{
		// There should be an uploaded file now
		if (!file_exists($_FILES["downloadfile"]["tmp_name"])) {
			return -2;
		}
		
		// Move the file over from temporary location to our files directory
		$storedfilename = buildHash();
		if (!move_uploaded_file($_FILES["downloadfile"]["tmp_name"], "./files/".$storedfilename))
		{
			return -3;
		}

		// Delete old file
		if (file_exists("./files/".$_downloaditem["storedfilename"]) && !empty($_downloaditem["storedfilename"]))
		{
			unlink("./files/".$_downloaditem["storedfilename"]);
		}

		$filesql = ", `filename` = '". $dbCore->escape($_FILES["downloadfile"]["name"]) ."', `storedfilename` = '". $dbCore->escape($storedfilename) ."', `filesize` = '". $dbCore->escape($_FILES["downloadfile"]["size"]) ."', `filetype` = '". $dbCore->escape($_FILES["downloadfile"]["type"]) ."'";
		unset($filelink);
	} else if (!empty($filelink)) {
		$filesql = ", `filename` = '', `storedfilename` = '', `filesize` = '0', `filetype` = ''";
	}
	

	if ($enablepassword == 1 && !empty($itempassword))
	{
		$finalitempassword = ", `itempassword` = '".md5($itempassword)."'";
	} else if ($enablepassword == 1 && empty($itempassword)) {
		unset($finalitempassword);
	} else {
		$finalitempassword = ", `itempassword` = ''";
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."downloaditems` SET `downloadcategoryid` = '". intval($downloadcategoryid) ."', `title` = '". $dbCore->escape($title) ."', `filelink` = '". $dbCore->escape($filelink) ."'". $filesql .", `displayorder` = '". intval($displayorder) ."', `updatedateline` = '". DATENOW ."'". $finalitempassword ." WHERE `downloaditemid` = '". intval($downloaditemid) ."';");

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."downloaddesc` SET `description` = '". $dbCore->escape($description) ."' WHERE `downloaditemid` = '". intval($downloaditemid) ."';");

	rebuildDownloadJSCache();
	recountDownloadCategory($downloadcategoryid);

	return $downloaditemid;
}

/**
* Add a download file to the database
*/
function addDownloadFile($downloadcategoryid, $title, $description, $filelink, $displayorder, $itempassword)
{
	global $dbCore, $_SWIFT;

	// Are we supposed to upload a file or just link over to an existing one?
	if (empty($filelink))
	{
		// There should be an uploaded file now
		if (!isset($_FILES["downloadfile"]))
		{
			return -1;
		} else if (!file_exists($_FILES["downloadfile"]["tmp_name"])) {
			return -2;
		}		

		// Move the file over from temporary location to our files directory
		$storedfilename = buildHash();
		if (!move_uploaded_file($_FILES["downloadfile"]["tmp_name"], "./files/".$storedfilename))
		{
			return -3;
		}
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."downloaditems` (`downloadcategoryid`, `downloadmaskid`, `title`, `version`, `filelink`, `filename`, `storedfilename`, `filesize`, `filetype`, `totaldownloads`, `displayorder`, `dateline`, `updatedateline`, `itempassword`) VALUES ('". intval($downloadcategoryid) ."', '', '". $dbCore->escape($title) ."', '". 0 ."', '". $dbCore->escape($filelink) ."', '". $dbCore->escape($_FILES["downloadfile"]["name"]) ."', '". $dbCore->escape($storedfilename) ."', '". $dbCore->escape($_FILES["downloadfile"]["size"]) ."', '". $dbCore->escape($_FILES["downloadfile"]["type"]) ."', '0', '". intval($displayorder) ."', '". DATENOW ."', '0', '". $dbCore->escape(iif(!empty($itempassword), md5($itempassword))) ."');");
	$downloaditemid = $dbCore->lastInsertId();

	if (!$downloaditemid)
	{
		return -4;
	}

	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."downloaddesc` (`downloaditemid`, `description`) VALUES ('". intval($downloaditemid) ."', '". $dbCore->escape($description) ."');");

	recountDownloadCategory($downloadcategoryid);
	rebuildDownloadJSCache();

	return $downloaditemid;
}

/**
* Delete an existing download item
*/
function deleteDownloadFiles($downloaditemidlist)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($downloaditemidlist))
	{
		return false;
	}

	$downloadfilelist = $downloadcategoryidlist = array();

	$dbCore->query("SELECT `storedfilename`, `downloadcategoryid` FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloaditemid` IN (". buildIN($downloaditemidlist) .");");
	while ($dbCore->nextRecord())
	{
		if (!empty($dbCore->Record["storedfilename"]))
		{
			$downloadfilelist[] = $dbCore->Record["storedfilename"];
		}
		if (!in_array($dbCore->Record["downloadcategoryid"], $downloadcategoryidlist))
		{
			$downloadcategoryidlist[] = $dbCore->Record["downloadcategoryid"];
		}
	}

	foreach ($downloadfilelist as $key=>$val)
	{
		// First unlink the file
		if (file_exists("./files/".$val) && !empty($val))
		{
			unlink("./files/".$val);
		}
	}

	// Now delete the actual entries
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloaditemid` IN (". buildIN($downloaditemidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."downloaddesc` WHERE `downloaditemid` IN (". buildIN($downloaditemidlist) .");");

	// Now update the category count
	foreach ($downloadcategoryidlist as $key=>$val)
	{
		recountDownloadCategory($val);
	}
	rebuildDownloadJSCache();

	return true;
}

/**
* Recalculate the number of files under a download category recursively
*/
function recountDownloadCategory($downloadcategoryid)
{
	global $dbCore;

	$_totalitems = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."downloaditems` WHERE `downloadcategoryid` = '". intval($downloadcategoryid) ."';");
	if (empty($_totalitems["totalitems"]))
	{
		$_total = 0;
	} else {
		$_total = $_totalitems["totalitems"];
	}

	$dbCore->query("UPDATE LOW_PRIORITY `". TABLE_PREFIX ."downloadcategories` SET `totalitems` = '". intval($_total) ."' WHERE `downloadcategoryid` = '". intval($downloadcategoryid) ."';");

	return true;
}

/**
* Builds a category array for all download categories
*/
function buildDLCategoryData($downloadcategoryidlist = false, $filtertgroupid = false)
{
	global $dbCore, $_SWIFT;

	if (isset($_SWIFT["dlcatcache"]))
	{
		return $_SWIFT["dlcatcach"];
	}
	
	$categorydata = $categoryidlist = array();
	$catcount = 0;
	if (_is_array($downloadcategoryidlist))
	{
		$wheresql = " WHERE downloadcategories.downloadcategoryid IN (". buildIN($downloadcategoryidlist) .")";
	} else {
		unset($wheresql);
	}

	if ($filtertgroupid)
	{
		$dofilter = true;
	} else {
		$dofilter = false;
	}

	if ($dofilter == true)
	{
		$dbCore->query("SELECT downloadcategories.* FROM `". TABLE_PREFIX ."downloadcategories` AS downloadcategories LEFT JOIN `". TABLE_PREFIX ."tgroupassigns` AS tgroupassigns ON (downloadcategories.downloadcategoryid = tgroupassigns.toassignid AND tgroupassigns.type = '". TGROUP_DOWNLOADS ."') WHERE tgroupassigns.tgroupid = '". intval($filtertgroupid) ."' ORDER BY downloadcategories.downloadcategoryid ASC;");
	} else {
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."downloadcategories` AS downloadcategories". $wheresql ." ORDER BY downloadcategories.downloadcategoryid ASC;");
	}
	while ($dbCore->nextRecord())
	{
		// We always add the download category to list if filtering isnt enabled
		$catcount = count($categorydata[$dbCore->Record["parentcategoryid"]]);
		$categorydata[$dbCore->Record["parentcategoryid"]][$catcount] = $dbCore->Record;
		$categoryidlist[] = $dbCore->Record["downloadcategoryid"];
	}

	$result["categorydata"] = $categorydata;
	$result["categoryidlist"] = $categoryidlist;
	$_SWIFT["dlcatcache"] = $result;
	return $result;
}

/**
* Builds a list of download items from given categories
*/
function buildDLItemData($downloadcategoryidlist = false)
{
	global $dbCore, $_SWIFT;
	
	$itemdata = array();
	$catcount = 0;

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."downloaditems` ORDER BY `downloaditemid` ASC;");
	while ($dbCore->nextRecord())
	{
		$itemdata[$dbCore->Record["downloadcategoryid"]][] = $dbCore->Record;
	}

	return $itemdata;
}

/**
* Rebuilds the download javascript cache
*/
function rebuildDownloadJSCache()
{
	global $_SWIFT;

	// ======= FIRST BUILD ALL THE ARTICLE DATA =======
	$itemdata = buildDLItemData();
	$jsdata = "dlmenuloaded = true;";
	// ======= NOW BUILD THE MENU =======
	$jsdata .= SWIFT_CRLF.SWIFT_CRLF;
	$categoryresult = buildDLCategoryData(false);
	$categorydata = $categoryresult["categorydata"];
	unset($categoryresult);

	$jsdata .= 'var MENU_JSCACHE_DOWNLOADS = ['.SWIFT_CRLF;
	$jsdata .= '	{"popup":1, "popupoff":[0,0], "pos":[0,0], "size":[22,250], "itemoff":[21,0], "leveloff":[10,59],dynamic: true, https_fix_blank_doc:themepath+"blank.html", "delay":600, "style":STYLEPOPUP, "imgsize":[20,22]},'.SWIFT_CRLF;
	$menudata = "";
	$jsdata .= doDLMenuLoop(0, $categorydata, $itemdata, $menudata, 1);
	$jsdata .= '];'.SWIFT_CRLF;
	insertToJSCache("downloads", $jsdata);
}

/**
* Does a loop on categories and data to generate the menu
*/
function doDLMenuLoop($categoryid, &$categorydata, &$itemdata, &$menudata, $indent=0)
{
	global $_SWIFT;
	
	$childcount = count($categorydata[$categoryid]);
	$itemcount = count($itemdata[$categoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	$childindent = str_repeat("  ", $indent);
	
	// ======= PROCESS ARTICLES =======
	if ($itemcount != 0)
	{
		$menudata2 = processMenuDLItems($categoryid, $itemdata, $childindent);
	}

	if ($childcount != 0)
	{
		// We itterate through all the childs
		$wrapindex = 0;
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$categoryid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($categorydata[$childdata["downloadcategoryid"]]);
			if ($wrapindex >= 15)
			{
				$dowrap = true;
				$wrapindex = 0;
			} else {
				$dowrap = false;
			}
			if ($ii == 0 || $dowrap == true)
			{
				$mstyle = "VSTYLEBORDER";
			} else {
				$mstyle = "VSTYLE";
			}

			$menudata .= $childindent.'{code:"'. addslashes($childdata["title"]) .'"'. iif($dowrap, ', wrapPoint:true') .', url:"javascript:void(0);", "format":{'. iif($categoryid==0&&$ii==0, '"itemoff":[0,0], ', '"itemoff":[21,0], ') .'"arrow":themepath+"icon_rightarrowgray.gif", "oarrow":themepath+"icon_rightarrowgray.gif", "arrsize":[10,10], "image":themepath+"icon_menufolder.gif", "oimage":themepath+"icon_menufolder.gif", "style":'. $mstyle .'}';
			$wrapindex++;

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				$childindentfw = str_repeat("  ", ($indent+1));
				$childindentfw2 = str_repeat("  ", ($indent+2));
				$menudata .= ",".SWIFT_CRLF;
				$menudata .= $childindentfw.'sub:['.SWIFT_CRLF;
				$menudata .= $childindentfw2 . '{"leveloff":[20,90], wrapoff:[\'level\',\'+previousItem-1px\']},'.SWIFT_CRLF;

				// Yup, do another loop for this
				$index++;
				doDLMenuLoop($childdata["downloadcategoryid"], $categorydata, $itemdata, $menudata, ($indent+2));
				$menudata .= $childindentfw.']'.SWIFT_CRLF;
				if (($ii+1) == $childcount && $itemcount == 0)
				{
					$menudata .= $childindent.'}'.SWIFT_CRLF;
				} else {
					$menudata .= $childindent.'},'.SWIFT_CRLF;
				}
			} else if ($subchilds == 0 && count($itemdata[$childdata["downloadcategoryid"]]) != 0) {
				// We have just replies under this category
				$childindentfw = str_repeat("  ", ($indent+1));
				$childindentfw2 = str_repeat("  ", ($indent+2));
				$menudata .= ",".SWIFT_CRLF;
				$menudata .= $childindentfw.'sub:['.SWIFT_CRLF;
				$menudata .= $childindentfw2 . '{"leveloff":[20,90], wrapoff:[\'level\',\'+previousItem-1px\']},'.SWIFT_CRLF;

				// Yup, do another loop for this
				$index++;
				$menudata .= processMenuDLItems($childdata["downloadcategoryid"], $itemdata, str_repeat("  ", ($indent+2)));
				$menudata .= $childindentfw.']'.SWIFT_CRLF;
				if (($ii+1) == $childcount && $itemcount == 0)
				{
					$menudata .= $childindent.'}'.SWIFT_CRLF;
				} else {
					$menudata .= $childindent.'},'.SWIFT_CRLF;
				}
			} else {
				if (($ii+1) == $childcount && $itemcount == 0)
				{
					$menudata .= "}".SWIFT_CRLF;
				} else {
					$menudata .= "},".SWIFT_CRLF;
				}
			}
		}
	}

	$menudata .= $menudata2;
	
	return $menudata;
}

/**
* Process the items and generate relevant JS
*/
function processMenuDLItems($downloadcategoryid, &$itemdata, $childindent)
{
	$itemcount = count($itemdata[$downloadcategoryid]);
	if ($itemcount != 0)
	{
		$wrapindex = 0;
		for ($ii=0; $ii<$itemcount; $ii++)
		{
			$childdata = &$itemdata[$downloadcategoryid][$ii];
			$index = $ii+$index;

			$aimage = "icon_menukbarticle.gif";
			if ($wrapindex >= 15)
			{
				$dowrap = true;
				$wrapindex = 0;
			} else {
				$dowrap = false;
			}
			if ($ii == 0 || $dowrap == true)
			{
				$mstyle = "VSTYLEBORDER";
			} else {
				$mstyle = "VSTYLE";
			}

			$menudata2 .= $childindent.'{code:"'. addslashes(iif(strlen($childdata["title"])>30, substr($childdata["title"],0,30)."...", $childdata["title"])) .'"'. iif($dowrap, ', wrapPoint:true') .', url:"javascript:autoInsertDL(\''. intval($childdata["downloaditemid"]) .'\', \''. addslashes($childdata["filelink"]) .'\', \''. addslashes($childdata["title"]) .'\');", "format":{"itemoff":[21,0], "image":themepath+"'. $aimage .'", "oimage":themepath+"'. $aimage .'", "style":'. $mstyle .'}';
			$wrapindex++;

			if (($ii+1) == $itemcount)
			{
				$menudata2 .= "}".SWIFT_CRLF;
			} else {
				$menudata2 .= "},".SWIFT_CRLF;
			}
		}

		return $menudata2;
	}
}

/**
* Does a loop on categories to generate tree view data
*/
function doDLCategoryTreeLoop($downloadcategoryid, $categorydata, $itemdata, &$nodeclass)
{
	global $_SWIFT;

	$childcount = count($categorydata[$downloadcategoryid]);
	$itemcount = count($itemdata[$downloadcategoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		// We itterate through all the childs
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$downloadcategoryid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($categorydata[$childdata["downloadcategoryid"]]);

			// Add this node to our parent node
			$_newnode = &$nodeclass->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $childdata["title"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[". iif($_SWIFT["staff"]["dlcaninsertfile"]!="0", " <a href='index.php?_m=downloads&_a=insertfile&parentcategoryid=". $childdata["downloadcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addfile"] ."'>". $_SWIFT["language"]["addfile"] ."</a>"). iif($_SWIFT["staff"]["dlcaninsertcat"]!="0", " | <a href='index.php?_m=downloads&_a=insertcategory&parentcategoryid=". $childdata["downloadcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addsubcat"] ."'>". $_SWIFT["language"]["addsubcat"] ."</a>"). iif($_SWIFT["staff"]["dlcaneditcat"]!="0", " | <a href='index.php?_m=downloads&_a=editcategory&downloadcategoryid=". $childdata["downloadcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["edit"] ."'>". $_SWIFT["language"]["edit"] ."</a>"). iif($_SWIFT["staff"]["dlcandelcat"]!="0", " | <a onClick='javascript:doConfirm(\"". $_SWIFT["language"]["dlcatdelconfirmmsg"] ."\", \"index.php?_m=downloads&_a=managecategories&do=delete&downloadcategoryid=". $childdata["downloadcategoryid"] ."\");' href='#' id='blue' title='". $_SWIFT["language"]["delete"] ."'>". $_SWIFT["language"]["delete"] ."</a> ")."]", 'link' => "", 'icon' => "icon_folderyellow3.gif", 'expandedIcon' => 'icon_folderyellow3.gif', 'expanded' => true)));

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				// Yup, do another loop for this
				$index++;
				doDLCategoryTreeLoop($childdata["downloadcategoryid"], $categorydata, $itemdata, $_newnode);
			}
		}
	}
	
	return true;
}

/**
* Builds a treeview like category select data
*/
function buildDLCategorySelectData($selectedcatid=0)
{
	global $_SWIFT, $dbCore;

	// Now fetch all the data for all download categories
	$result = buildDLCategoryData();
	$categorydata = $result["categorydata"];

	// Build the option tree for this category
	$_option = array();
	doDLCategoryOptionLoop(0, $categorydata, $selectedcatid, 1, ($index=1), $_option);

	$_option[0]["title"] = $_SWIFT["language"]["downloadscat"];
	$_option[0]["value"] = "0";
	$_option[0]["selected"] = iif($selectedcatid==0, true, false);

	return $_option;
}

/**
* Does a loop on categories to generate data
*/
function doDLCategoryOptionLoop($downloadcategoryid, $categorydata, $selectedcatid=0, $indent=0, &$index, &$_option)
{
	$childcount = count($categorydata[$downloadcategoryid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		$childindent = str_repeat("  ", $indent);
		$childprefix = $childindent."|- ";

		// Iterate through all childs and build the option list
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorydata[$downloadcategoryid][$ii];
			$_option[$index]["title"] = $childprefix.$childdata["title"];
			$_option[$index]["value"] = $childdata["downloadcategoryid"];
			$_option[$index]["selected"] = iif($selectedcatid == $childdata["downloadcategoryid"], true, false);
			$index++;

			// Does it have any sub childs?
			if (count($categorydata[$childdata["downloadcategoryid"]]) > 0)
			{
				// Yup, do another loop for this
				doDLCategoryOptionLoop($childdata["downloadcategoryid"], $categorydata, $selectedcatid, ($indent+1), $index, $_option);
			}
		}
	}
	
	return $_option;
}

/**
* Update existing downloads category
*/
function updateDownloadsCategory($downloadcategoryid, $parentcategoryid, $title, $displayorder, $categorytype, $tgroupidlist)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."downloadcategories` SET `parentcategoryid` = '". intval($parentcategoryid) ."', `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `title` = '". $dbCore->escape($title) ."', `dateline` = '". DATENOW ."', `categorytype` = '". $dbCore->escape($categorytype) ."', `displayorder` = '". intval($displayorder) ."' WHERE `downloadcategoryid` = '". intval($downloadcategoryid) ."';");

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_DOWNLOADS, $downloadcategoryid, true);

	rebuildDownloadJSCache();

	return $downloadcategoryid;
}

/**
* Inserts a new downloads category
*/
function insertDownloadsCategory($parentcategoryid, $title, $displayorder, $categorytype, $tgroupidlist)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."downloadcategories` (`parentcategoryid`, `staffid`, `title`, `dateline`, `totalitems`, `categorytype`, `displayorder`) VALUES ('". intval($parentcategoryid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($title) ."', '". DATENOW ."', '0', '". $dbCore->escape($categorytype) ."', '". intval($displayorder) ."');");
	$downloadcategoryid = $dbCore->lastInsertId();
	if (!$downloadcategoryid)
	{
		return false;
	}

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_DOWNLOADS, $downloadcategoryid, false);

	rebuildDownloadJSCache();

	return $downloadcategoryid;
}

/**
* Render the INSERT/EDIT Form for Downloads Categories
*/
function renderDownloadsCatForm($type)
{
	global $_SWIFT, $dbCore;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["dlcatdetails"]);

	// Title
	printTextRow("title", $_SWIFT["language"]["dlcattitle"], $_SWIFT["language"]["desc_dlcattitle"], "text", $_POST["title"]);

	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the download category.. will be done only for insert action
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."downloadcategories` ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}		
	}
	printNumberRow("displayorder", $_SWIFT["language"]["dlcatdisporder"], $_SWIFT["language"]["desc_dlcatdisporder"], $_POST["displayorder"]);

	$_options = buildDLCategorySelectData(iif(empty($_REQUEST["parentcategoryid"]), 0, $_REQUEST["parentcategoryid"]));
	printSelectRow("parentcategoryid", $_SWIFT["language"]["parentcategory"], $_SWIFT["language"]["desc_parentcategory"], $_options);

	$categorytype = false;
	if ($type == INSERT)
	{
		$categorytype = true;
	} else {
		if ($_POST["categorytype"] == SWIFTPUBLIC)
		{
			$categorytype = true;
		}
	}
	printPublicPrivateRow("categorytype", $_SWIFT["language"]["cattype"], $_SWIFT["language"]["desc_cattype"], $categorytype);

	printTGroupRow("tgroupid", $_SWIFT["language"]["templategroups"], $_SWIFT["language"]["desc_templategroups"], $type, TGROUP_DOWNLOADS, $_POST["downloadcategoryid"]);

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertdlcat"], $_SWIFT["language"]["updatedlcat"]));

	printMainTableFooter();

	addHiddenField("_m", "downloads");
	addHiddenField("_a", iif($type==INSERT, "insertcategory", "editcategory"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("downloadcategoryid", $_POST["downloadcategoryid"]);
	}
	printFormEnd();
}

/**
* Render the INSERT/EDIT Form for Download Items
*/
function renderDownloadItemsForm($type)
{
	global $_SWIFT, $dbCore;

	printFormStart("downloadfileform", "index.php", "POST", true);
	printMainTableHeader($_SWIFT["language"]["dlfiledetails"]);

	// Title
	printTextRow("title", $_SWIFT["language"]["dlitemtitle"], $_SWIFT["language"]["desc_dlitemtitle"], "text", $_POST["title"]);

	// Description
	printTextareaRow("description", $_SWIFT["language"]["dlitemdesc"], $_SWIFT["language"]["desc_dlitemdesc"], $_POST["description"]);

	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the download items.. will be done only for insert action
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."downloaditems` ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}		
	}
	printNumberRow("displayorder", $_SWIFT["language"]["dlfiledisplayorder"], $_SWIFT["language"]["desc_dlfiledisplayorder"], $_POST["displayorder"]);

	$_options = buildDLCategorySelectData(iif(empty($_REQUEST["parentcategoryid"]), 0, $_REQUEST["parentcategoryid"]));
	printSelectRow("downloadcategoryid", $_SWIFT["language"]["parentcategory"], $_SWIFT["language"]["desc_parentcategory"], $_options);

	printDescRow($_SWIFT["language"]["filetype"]);
	printUploadRow("downloadfile", $_SWIFT["language"]["dlitemfile"], $_SWIFT["language"]["desc_dlitemfile"], "25");
	printTextRow("filelink", $_SWIFT["language"]["dlitemfilelink"], $_SWIFT["language"]["desc_dlitemfilelink"], "text", $_POST["filelink"]);

	// ======= PASSWORD =======
	if (!empty($_POST["itempassword"]))
	{
		$passprotection = true;
	}
	printDescRow($_SWIFT["language"]["passwordprotection"]);
	printYesNoRow("enablepassword", $_SWIFT["language"]["enablepassword"], $_SWIFT["language"]["desc_enablepassword"], $passprotection);
	printTextRow("password", iif($type==EDIT, $_SWIFT["language"]["resetpassword"], $_SWIFT["language"]["password"]), $_SWIFT["language"]["desc_password"], "password", $_POST["password"], "20");
	printTextRow("passwordconfirm", $_SWIFT["language"]["passwordconfirm"], $_SWIFT["language"]["desc_passwordconfirm"], "password", $_POST["passwordconfirm"], "20");

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertfile"], $_SWIFT["language"]["updatefile"]));

	printMainTableFooter();

	addHiddenField("_m", "downloads");
	addHiddenField("_a", iif($type==INSERT, "insertfile", "editfile"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("downloaditemid", $_POST["downloaditemid"]);
	}
	printFormEnd();
}

/**
* Renders the Category List
*/
function renderCategoryList()
{
	global $dbCore, $template;

	$mcategories = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."downloadcategories` WHERE `parentcategoryid` = '0';");
	while ($dbCore->nextRecord())
	{
		$mcategories[$dbCore->Record["downloadcategoryid"]] = $dbCore->Record;
		$mcategories[$dbCore->Record["downloadcategoryid"]]["title"] = iif(strlen($dbCore->Record["title"])>15, substr($dbCore->Record["title"],0,15)."..", $dbCore->Record["title"]);
		$mcategories[$dbCore->Record["downloadcategoryid"]]["link"] = "index.php?_m=downloads&_a=managefiles&filter=1&filterdownloadcategoryid=".intval($dbCore->Record["downloadcategoryid"]);
	}

	if (count($mcategories))
	{
		$template->assign("catlist", true);
		$template->assign("mcategories", $mcategories);
	}

	return true;
}
?>